package com.test.nnooolwdeaer.util_wooden.http_wooden;

import static com.test.nnooolwdeaer.bean_wooden.StaticVariate_wooden.Country_Word_wooden;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.test.nnooolwdeaer.activity_fragment_wooden.base_wooden.BaseApplication_wooden;
import com.test.nnooolwdeaer.constant_wooden.UserInfoData_wooden;
import com.test.nnooolwdeaer.dec_wooden.Demo_wooden;
import com.test.nnooolwdeaer.util_wooden.StringUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.ThreadUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.analytics_wooden.util_wooden.AnalyticsUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.event.TrackManager_wooden;
import com.test.nnooolwdeaer.util_wooden.helper_wooden.UserInfoHelper_wooden;
import com.test.nnooolwdeaer.bean_wooden.StaticVariate_wooden;
import com.test.nnooolwdeaer.constant_wooden.Constant_wooden;
import com.test.nnooolwdeaer.constant_wooden.Url_wooden;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Objects;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;

public class HttpManager_wooden {

    private HttpManager_wooden() {

        mHttpLoggingInterceptor_wooden.setLevel(HttpLoggingInterceptor.Level.BODY);

        mClient_wooden = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addNetworkInterceptor(mHttpLoggingInterceptor_wooden)
                .addInterceptor(new ReqInterceptor_wooden())
                .callTimeout(30000, TimeUnit.MILLISECONDS)
                .build();
    }

    private static class Inner_wooden {
        private static final HttpManager_wooden instance_wooden = new HttpManager_wooden();
    }

    public static HttpManager_wooden getInstance_wooden() {
        return Inner_wooden.instance_wooden;
    }

    private static OkHttpClient mClient_wooden;

    //tag2025
    private static final HttpLoggingInterceptor mHttpLoggingInterceptor_wooden = new HttpLoggingInterceptor(new HttpLogger_wooden());

    //请求响应回调
    private final Callback callback_wooden = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            HttpPresenter_wooden.getInstance_wooden().showToastOnUiThread_wooden("Request Fail");
            ThreadUtil_wooden.getInstance_wooden().runOnUiThread_wooden(() -> HttpPresenter_wooden.getInstance_wooden().progressBarDialogDismiss_wooden());
            Log.e("Http Response", "Request Fail");
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            String body = Objects.requireNonNull(response.body()).string();
            ThreadUtil_wooden.getInstance_wooden().runOnUiThread_wooden(() -> HttpPresenter_wooden.getInstance_wooden().progressBarDialogDismiss_wooden());
            try {
                String word = StringUtil_wooden.getUrlSuffix_wooden(response.request().url().toString());
                handleResponse_wooden(word, new JSONObject(body));
            } catch (JSONException e) {
                if (Constant_wooden.Debug) e.printStackTrace();
            }
        }
    };

    //处理响应
    private void handleResponse_wooden(String lastWord, JSONObject responseJson) {
        ThreadUtil_wooden.getInstance_wooden().runOnUiThread_wooden(() -> HttpPresenter_wooden.getInstance_wooden().notifyActivityHandleResponse_wooden(lastWord, responseJson));
    }

    //获取初始化JSON对象
    @NonNull
    private JSONObject getRequestJson_wooden() {
        return getRequestJson_wooden(new JSONObject());
    }

    private JSONObject getRequestJson_wooden(JSONObject jsonObject) {
        try {
            jsonObject.put("isLimitAdTrackingEnabled", AnalyticsUtil_wooden.INSTANCE.getAdEnabled() + "");
            jsonObject.put("aduid", AnalyticsUtil_wooden.INSTANCE.getAdId());
            jsonObject.put("aduidPath", AnalyticsUtil_wooden.INSTANCE.getAndroidId());
            jsonObject.put("version", BaseApplication_wooden.getApplication().versionCodeStr().trim());
            jsonObject.put("token", UserInfoHelper_wooden.getInstance_wooden().getToken_wooden().trim());
            jsonObject.put("androidId", AnalyticsUtil_wooden.INSTANCE.getAndroidId());
            jsonObject.put("userId", UserInfoHelper_wooden.getInstance_wooden().getUserId_wooden().trim());
            jsonObject.put("advertId", AnalyticsUtil_wooden.INSTANCE.getAdId());
            jsonObject.put("product", Constant_wooden.PRODUCT_wooden.trim());
            jsonObject.put("clientType", Constant_wooden.CLIENT_wooden.trim());
            jsonObject.put("localTimestamp", String.valueOf(System.currentTimeMillis()));
            jsonObject.put("apiVersion", "v3");
            return jsonObject;
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        return jsonObject;
    }

    //发送请求
    private void request_wooden(String lastWord, String jsonString) {
        requestWithoutCountryPrefix_wooden(StaticVariate_wooden.getCountryUrlPrefix_wooden() + lastWord,jsonString);
    }

    //发送请求（不带国家前缀）
    private void requestWithoutCountryPrefix_wooden(String lastWord, String jsonString) {

        if (TextUtils.isEmpty(jsonString)) return;

        ThreadUtil_wooden.getInstance_wooden().runOnUiThread_wooden(() -> HttpPresenter_wooden.getInstance_wooden().progressBarDialogShow_wooden());

        ThreadUtil_wooden.getInstance_wooden().runOnChildThread_wooden(() -> {
            try {
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                Request request = new Request.Builder()
                        .url(StaticVariate_wooden.getBaseUrl() + lastWord)
                        .post(RequestBody.Companion.create(jsonString, mediaType))
                        .build();
                Call call = mClient_wooden.newCall(request);
                call.enqueue(callback_wooden);
            }catch (Exception e){
                if (Constant_wooden.Debug) e.printStackTrace();
            }
        });
    }

    public void requestForDevice(String lastWord, String jsonString){

        if (TextUtils.isEmpty(jsonString)) return;

        final String fLastWord = StaticVariate_wooden.getCountryUrlPrefix_wooden() + lastWord;

        ThreadUtil_wooden.getInstance_wooden().runOnChildThread_wooden(() -> {
            try {
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                Request request = new Request.Builder()
                        .url(StaticVariate_wooden.getBaseUrl() + fLastWord)
                        .post(RequestBody.Companion.create(jsonString, mediaType))
                        .build();
                Call call = mClient_wooden.newCall(request);
                call.execute();
            } catch (Exception e) {
                if (Constant_wooden.Debug) e.printStackTrace();
            }

        });
    }

    //global信息
    public void queryGlobal_wooden() {
        requestWithoutCountryPrefix_wooden(Url_wooden.PATH_GLOBAL, getRequestJson_wooden().toString());
    }

    //获取App配置
    public void getAppShowInfo_wooden() {
        request_wooden(Url_wooden.PATH_APP_SHOW_INFO, getRequestJson_wooden().toString());
    }

    //获取登录验证码
    public void requestOtpCode_wooden(String phoneNum) {
        UserInfoHelper_wooden.getInstance_wooden().setMobile_wooden(StringUtil_wooden.getSafeString_wooden(phoneNum));
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("mobile", phoneNum.trim());
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_SMS_CODE, jsonObject.toString());
    }

    //注册登录-有验证码
    public void userLogin_wooden(String phoneNum, String verCode) {
        UserInfoHelper_wooden.getInstance_wooden().setMobile_wooden(StringUtil_wooden.getSafeString_wooden(phoneNum));
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_wooden.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_wooden.INSTANCE.getInstallReferrer());
            jsonObject.put("code", verCode.trim());
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("notBindWalletFlag", "YES");
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_USER_LOGIN, jsonObject.toString());
    }

    //注册登录-老用户
    public void userLoginOldUser_wooden(String phoneNum) {
        UserInfoHelper_wooden.getInstance_wooden().setMobile_wooden(StringUtil_wooden.getSafeString_wooden(phoneNum));
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("channelCode", AnalyticsUtil_wooden.INSTANCE.getInstallReferrer());
            jsonObject.put("subChannelCode", AnalyticsUtil_wooden.INSTANCE.getInstallReferrer());
            jsonObject.put("code", "0000");
            jsonObject.put("mobile", phoneNum.trim());
            jsonObject.put("directLoginFlag","YES");
            jsonObject.put("notBindWalletFlag","YES");
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_USER_LOGIN, jsonObject.toString());
    }

    public void submitServiceFeedback_wooden(String type, String opinion) {
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("type", type);
            jsonObject.put("opinion", opinion);
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_FEED_BACK, jsonObject.toString());
    }

    //获取银行列表（尼日）
    public void fetchBankCodes_Niri_wooden() {
        request_wooden(Url_wooden.PATH_FETCH_BANK_CODE, getRequestJson_wooden().toString());
    }

    //获取钱包列表（科特）
    public void fetchBoundBankAccount_Cote_wooden() {
        request_wooden(Url_wooden.PATH_FETCH_BOUND_BANK_ACCOUNT, getRequestJson_wooden().toString());
    }

    //新增钱包（科特）
    public void bindBankAccount_wooden(String walletMobile, String walletMobileConfirm, String walletChannel) {
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("walletMobile", walletMobile);
            jsonObject.put("walletMobileConfirm", walletMobileConfirm);
            jsonObject.put("walletChannel", walletChannel);
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_BIND_BANK_ACCOUNT, jsonObject.toString());
    }

    //删除钱包（科特）
    public void deleteBoundBankAccount_wooden(String ids) {
        JSONObject jsonObject = getRequestJson_wooden();
        try {
            jsonObject.put("ids", ids);
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_DELETE_BOUND_BANK_ACCOUNT, jsonObject.toString());
    }

    //请求用户流程状态
    public void requestUserProcess_wooden() {
        request_wooden(Url_wooden.PATH_USER_PROCESS, getRequestJson_wooden().toString());
    }

    //上传用户信息
    public void uploadInfo_wooden(String url, TreeMap<String, String> dataMap) {
        try {
            JSONObject jsonObject = getRequestJson_wooden();
            for (String k : dataMap.keySet()) {
                String key = StringUtil_wooden.getSafeString_wooden(k);
                String value = StringUtil_wooden.getSafeString_wooden(dataMap.get(k));
                jsonObject.put(key, value);
            }
            StaticVariate_wooden.Upload_Info_Url_wooden = url;
            String prefix = "/" + Country_Word_wooden;
            if (!url.startsWith(prefix)) url = prefix + url;
            requestWithoutCountryPrefix_wooden(url, jsonObject.toString());
        } catch (Exception e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
    }

    //请求额度列表
    public void queryLoanLimit_wooden() {
        request_wooden(Url_wooden.PATH_LOAN_LIMIT, getRequestJson_wooden().toString());
    }

    //请求借款申请页信息/贷款详情
    public void requestLoanApplyDetail_wooden() {
        request_wooden(Url_wooden.PATH_GET_LOAN_APPLY_DETAIL, getRequestJson_wooden().toString());
    }

    //发起借款申请
    public void loanApply_wooden() {
        request_wooden(Url_wooden.PATH_LOAN_APPLY, getRequestJson_wooden().toString());
    }

    //获取还款信息
    public void getRepayDetail_wooden() {
        request_wooden(Url_wooden.PATH_REPAY_INFO, getRequestJson_wooden().toString());
    }

    //获取还款H5（加纳、科特、越南）
    public void orderRepayH5_gh_cl_vi_wooden() {
        request_wooden(Url_wooden.PATH_ORDER_REPAY_H5, getRequestJson_wooden().toString());
    }

    //获取还款H5（乌干达、肯尼亚）
    public void orderRepayH5_ug_ke_wooden() {
        request_wooden(Url_wooden.PATH_GET_ORDER_REPAY_H5, getRequestJson_wooden().toString());
    }

    //初始化paystack订单（尼日）
    public void orderRepaySDK_wooden(String cardNumber, String expiryYear, String expiryMonth, String cvv) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("cardNumber", cardNumber.trim());
            jsonObject.put("expiryYear", expiryYear.trim());
            jsonObject.put("expiryMonth", expiryMonth.trim());
            jsonObject.put("cvv", cvv.trim());
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
        request_wooden(Url_wooden.PATH_ORDER_REPAY_SDK, getRequestJson_wooden(jsonObject).toString());
    }

    //获取paystack卡列表（尼日）
    public void bankList_niri_wooden() {
        request_wooden(Url_wooden.PATH_BANK_LIST, getRequestJson_wooden().toString());
    }

    //线下还款-创建虚拟账号还款
    public void createVirtualAccount_wooden() {
        request_wooden(Url_wooden.PATH_CREATE_VIRTUAL_ACCOUNT, getRequestJson_wooden().toString());
    }

    //获取证件Ocr信息（越南）
    public void getDiscernIcrInfo(String imageUrl){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("imageUrl",imageUrl);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        request_wooden(Url_wooden.Path_Get_Discern_Icr_Info, getRequestJson_wooden(jsonObject).toString());
    }

    //上传人脸照片信息（越南）
    public void faceRecognitionCheck(String imageUrl1,String imageUrl2){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("file1",imageUrl1);
            jsonObject.put("file2",imageUrl2);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        request_wooden(Url_wooden.Path_Face_Recognition_Check, getRequestJson_wooden(jsonObject).toString());
    }

    //获取运营商链接（越南）
    public void peratorInformation(){
        request_wooden(Url_wooden.Path_Perator_Information, getRequestJson_wooden().toString());
    }

    //保存运营商认证信息(越南)
    public void savePeratorInformation(){
        request_wooden(Url_wooden.Path_Save_Perator_Information, getRequestJson_wooden().toString());
    }

    public static String dropType = "GET";

    public void fetchDropConfig() {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("type", "GET");
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }

        dropType = "GET";

        request_wooden(Url_wooden.PATH_DROP_DATA, getRequestJson_wooden(jsonObject).toString());

    }

    public void dropUserData() {

        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("type", "DROP");
        } catch (JSONException e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }

        dropType = "DROP";

        request_wooden(Url_wooden.PATH_DROP_DATA, getRequestJson_wooden(jsonObject).toString());

    }


    /**
     * 上传图片
     */
    public void uploadImage(String filePath_equitable) {
        if (Looper.myLooper()!=Looper.getMainLooper())
            ThreadUtil_wooden.getInstance_wooden().runOnUiThread_wooden(() -> HttpPresenter_wooden.getInstance_wooden().progressBarDialogShow_wooden());
        else HttpPresenter_wooden.getInstance_wooden().progressBarDialogShow_wooden();
        try {
            if (!TextUtils.isEmpty(filePath_equitable)) {
                String fileSuffix_equitable = filePath_equitable.endsWith(".png") ? "image/png" : "image/jpg";
                final MediaType mediaType_equitable = MediaType.parse(fileSuffix_equitable);
                final File imageFile_equitable = new File(filePath_equitable);
                final String uplodUrl_equitable = StaticVariate_wooden.getBaseUrl()+StaticVariate_wooden.getCountryUrlPrefix_wooden() + Url_wooden.PATH_UPLOAD_IMAGE_FILE;

                if (imageFile_equitable.isFile()) {
                    RequestBody imageBody = RequestBody.create(mediaType_equitable, imageFile_equitable);

                    RequestBody requestBody_equitable = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("image", imageFile_equitable.getName(), imageBody)
                            .build();

                    Request request_equitable = new Request.Builder()
                            .url(uplodUrl_equitable)
                            .post(requestBody_equitable)
                            .build();

                    Call call = mClient_wooden.newCall(request_equitable);
                    call.enqueue(callback_wooden);
                }
            }
        } catch (Exception e) {
            if (Constant_wooden.Debug) e.printStackTrace();
        }
    }

    //获取评分弹窗信息
    public void fetchStarWindowConfig(){
        request_wooden(Url_wooden.PATH_FETCH_STAR_WINDOW_CONFIG, getRequestJson_wooden().toString());
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent) {
        TrackManager_wooden.INSTANCE.track(pageEvent.toUpperCase(),"");
    }

    /**
     * 保存页面显示/隐藏打点
     */
    public void saveUserBuriedPoint(String pageEvent, String remark) {
        TrackManager_wooden.INSTANCE.track(pageEvent.toUpperCase(),remark);
    }

    /**
     * 保存页面显示/隐藏打点 并上传
     */
    public void saveUserBuriedPointAndUpload(String pageEvent) {
        TrackManager_wooden.INSTANCE.trackNow(pageEvent.toUpperCase(),"");
    }

    /**
     * 保存页面显示/隐藏打点 并上传
     */
    public void saveUserBuriedPointAndUpload(String pageEvent, String remark) {
        TrackManager_wooden.INSTANCE.trackNow(pageEvent.toUpperCase(),remark);
    }

    public void uploadUSerBuriedPoint(JSONArray eventList, Runnable onSuccess){

        if (eventList == null || TextUtils.isEmpty(Country_Word_wooden)) return;

        if (Constant_wooden.Debug){
            Log.i("event_size", String.valueOf(eventList.length()));
            for (int i = 0; i < eventList.length(); i++) {
                JSONObject jsonObject = eventList.optJSONObject(i);
                if (jsonObject != null)
                    Log.i("event_detail", "id=" + jsonObject.optString("id") + ", type=" + jsonObject.optString("type") + ", remark=" + jsonObject.optString("remark"));
            }
        }

        new Thread(() -> {
            try {
                JSONObject jsonObject = getRequestJson_wooden();
                jsonObject.put("list", eventList);
                final String gurl = StaticVariate_wooden.getBaseUrl() + "/" + Country_Word_wooden + Url_wooden.PATH_USER_BURIED_POINT_FOR_BATCH;
                Request request = new Request.Builder()
                        .url(gurl)
                        .post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), jsonObject.toString()))
                        .build();

                Call call = mClient_wooden.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        if (Constant_wooden.Debug) Log.e("event-response", "Failed" );
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                        try {

                            ResponseBody responseBody = response.body();
                            if (responseBody == null) {
                                if (Constant_wooden.Debug) Log.e("event-response", "body is null" );
                                return;
                            }
                            String bodyStr = responseBody.string();
                            if (TextUtils.isEmpty(bodyStr)){
                                if (Constant_wooden.Debug) Log.e("event-response", "body is empty" );
                                return;
                            }

                            JSONObject responseJson = new JSONObject(bodyStr);
                            int code = -1;
                            if (responseJson.has("code")) code = Integer.parseInt(responseJson.optString("code"));
                            if (code==0 && onSuccess!=null) {
                                if (Constant_wooden.Debug) Log.i("event-response", "Successful" );
                                onSuccess.run();
                            }else if (code!=0 && Constant_wooden.Debug) Log.i("event-response", "code is not 0" );

                        } catch (Exception e){
                            if (Constant_wooden.Debug) e.printStackTrace();
                        }
                    }
                });
            } catch (Exception e) {
                if (Constant_wooden.Debug) e.printStackTrace();
            }
        }).start();

    }

    /**
     * 获取设备数据上报状态
     */
    public void fetchDeviceInfoType(){

        String url = StaticVariate_wooden.getBaseUrl() + StaticVariate_wooden.getCountryUrlPrefix_wooden() + Url_wooden.PATH_FETCH_DEVICE_INFO_TYPES;

        ThreadUtil_wooden.getInstance_wooden().runOnChildThread_wooden(() -> {
            try {
                Request request = new Request.Builder()
                        .url(url)
                        .post(RequestBody.Companion.create(getRequestJson_wooden().toString(), MediaType.Companion.parse("application/json;charset=utf-8")))
                        .build();
                Call call = mClient_wooden.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        uploadAllDeviceInfo();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        try {

                            ResponseBody responseBody = response.body();
                            if (responseBody == null) {
                                uploadAllDeviceInfo();
                                if (Constant_wooden.Debug) Log.e("device-response", "body is null" );
                                return;
                            }
                            String bodyStr = responseBody.string();
                            if (TextUtils.isEmpty(bodyStr)){
                                uploadAllDeviceInfo();
                                if (Constant_wooden.Debug) Log.e("device-response", "body is empty" );
                                return;
                            }

                            JSONObject responseJson = new JSONObject(bodyStr);
                            int code = Integer.parseInt(responseJson.optString("code"));

                            if (code!=0) {
                                uploadAllDeviceInfo();
                                if (Constant_wooden.Debug) {
                                    String msg = responseJson.optString("msg");
                                    Log.e("device-response", "failed,msg = " + StringUtil_wooden.getSafeString_wooden(msg));
                                }
                            }

                            JSONObject obj = responseJson.optJSONObject("obj");
                            if (obj!=null && obj.has("deviceInfoTypes")){
                                JSONArray jsonArray = obj.optJSONArray("deviceInfoTypes");
                                if (jsonArray!=null){

                                    ArrayList<String> list = new ArrayList<>();
                                    for (int i=0; i<jsonArray.length(); i++){
                                        list.add(jsonArray.optString(i));
                                    }

                                    new Demo_wooden(BaseApplication_wooden.getApplication()).upload(list);

                                }else {
                                    uploadAllDeviceInfo();
                                    if (Constant_wooden.Debug) Log.e("device-response", "failed,no obj array");
                                }
                            }else {
                                uploadAllDeviceInfo();
                                if (Constant_wooden.Debug) Log.e("device-response", "failed,no obj body");
                            }

                        }catch (Exception e){
                            if (Constant_wooden.Debug) e.printStackTrace();
                        }
                    }
                });
            }catch (Exception e){
                if (Constant_wooden.Debug) e.printStackTrace();
            }
        });
    }

    private void uploadAllDeviceInfo(){
        new Demo_wooden(BaseApplication_wooden.getApplication()).upload(new ArrayList<>(){{
            add("T1");
            add("T2");
            add("T3");
            add("T4");
            add("T5");
            add("T6");
            add("T7");
        }});
    }

}
